package com.katesoft.scale4j.agent;

import com.katesoft.scale4j.log.LogFactory;
import com.katesoft.scale4j.log.Logger;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Collection;
import java.util.LinkedHashSet;

import static java.util.Arrays.asList;
import static org.perf4j.helpers.MiscUtils.splitAndTrim;

/**
 * This class allows you to start application service from spring configuration files.
 * <p/>
 * Programs arguments threat as spring configuration files locations(also each parameter can be container of few location separated by comma).
 *
 * @author kate2007
 */
public class SpringConfigurationRunner
{
    private static final Logger LOGGER = LogFactory.getLogger(SpringConfigurationRunner.class);

    public static void main(String[] args)
    {
        Collection<String> locations = new LinkedHashSet<String>();
        for (String arg : args) {
            locations.addAll(asList(splitAndTrim(arg, ",")));
        }
        LOGGER.info("starting jvm using spring launcher with locations = %s", locations.toString());
        try {
            ClassPathXmlApplicationContext c = new ClassPathXmlApplicationContext(locations.toArray(new String[locations.size()]));
            c.registerShutdownHook();
            c.addApplicationListener(new ApplicationListener()
            {
                @Override
                public void onApplicationEvent(ApplicationEvent event)
                {
                    if (event instanceof ContextClosedEvent) {
                        LOGGER.info("spring application context %s get closed", ((ContextClosedEvent) event).getApplicationContext().getDisplayName());
                        Thread.currentThread().interrupt();
                    }
                }
            });
        }
        catch (Exception e) {
            LOGGER.error(e);
        }
    }
}
